import java.util.LinkedList;

public class Connect2 {

    public Node connect1(Node root) {
        if (root == null) return null;
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int k = queue.size();
            for (int i = 0; i < k; i++) {
                Node node = queue.poll();
                if (i != k - 1) {
                    node.next = queue.peek();
                }
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return root;
    }

    public void process(Node node) {
        if (node == null) return;
        Node temp = node;
        Node start = null;
        Node head = null;
        while (temp != null) {
            if (temp.left != null) {
                if (start != null) {
                    start.next = temp.left;
                    start = start.next;
                } else {
                    start = temp.left;
                    head = start;
                }
            }
            if (temp.right != null) {
                if (start != null) {
                    start.next = temp.right;
                    start = start.next;
                } else {
                    start = temp.right;
                    head = start;
                }
            }
            temp = temp.next;
        }
        process(head);
    }

    public Node connect(Node root) {
        if (root == null) return null;
        process(root);
        return root;
    }
}
